package capricornus.actor.res
{
	import capricornus.actor.events.ActionImageEvent;
	import capricornus.events.ResLoaderEvent;
	import capricornus.net.NetWorkManager;
	import capricornus.net.Path;
	import capricornus.net.loader.ActionImageLoader;
	import capricornus.net.loader.ResLoader;
	
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.utils.Dictionary;

	public class ActorImageManager extends EventDispatcher
	{
		public static const instance:ActorImageManager = new ActorImageManager();
		
		private var _dictActionImage:Dictionary;
		private var _dictLoader:Dictionary;
		
		public function ActorImageManager()
		{
			init();
		}
		
		private function init():void
		{
			_dictActionImage = new Dictionary();
			_dictLoader = new Dictionary();
		}
		
		//没有则返回null，null时监听 name+actionType 事件
		public function getActionImage( name:String, actionType:int ):ActionImage
		{
			var ai:ActionImage = _dictActionImage[name + actionType];
			if( ai==null ) 
			{
				loadImage( name, actionType );
			}
				
			return ai==null ? ai : ai.clone();
		}
		
		private function loadImage( name:String, type:int ):void
		{
			var url:String = Path.getActorImagePath( name, type );
			if( _dictLoader[url]==null )
			{
				var sl:ActionImageLoader = new ActionImageLoader();
				_dictLoader[url] = sl;
				sl.addEventListener( ResLoaderEvent.COMPLETE, onResLoaded, false, 0, true );
				sl.loadImage( name, type );
			}
		}
		
		private function onResLoaded( e:ResLoaderEvent ):void
		{
			var sl:ActionImageLoader = e.currentTarget as ActionImageLoader;
			delete _dictLoader[sl.url];
			var ai:ActionImage = e.data as ActionImage;
			if( ai != null )
			{
				_dictActionImage[sl.name + sl.type] = ai;
				dispatchEvent( new ActionImageEvent( sl.name + sl.type, sl.type ) );
			}
			else 
			{
				trace( "ActionImage load error: ", sl.url );
			}
			
			sl.destroy();
		}
	}
}




